import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// GET /api/task/[id]/comments - 获取特定任务的评论
export async function GET(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const taskId = context.params.id;
    const userId = session.user.id;
    
    // 查找任务
    const task = await prisma.task.findUnique({
      where: { id: taskId },
      select: { projectId: true }
    });
    
    if (!task) {
      return NextResponse.json(
        { success: false, message: '任务不存在' },
        { status: 404 }
      );
    }
    
    // 检查用户是否有权限访问该项目
    const projectUser = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId: task.projectId,
        },
      },
    });
    
    if (!projectUser) {
      return NextResponse.json(
        { success: false, message: '没有权限访问此任务的评论' },
        { status: 403 }
      );
    }
    
    // 查询评论
    const comments = await prisma.comment.findMany({
      where: { taskId },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
      },
      orderBy: { createdAt: 'asc' },
    });
    
    return NextResponse.json({ success: true, data: comments });
  } catch (error: any) {
    console.error('获取任务评论失败:', error);
    return NextResponse.json(
      { success: false, message: '获取任务评论失败', error: error.message },
      { status: 500 }
    );
  }
}

// POST /api/task/[id]/comments - 创建评论
export async function POST(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json(
        { success: false, message: '未授权' },
        { status: 401 }
      );
    }

    const taskId = context.params.id;
    const userId = session.user.id;
    const body = await request.json();
    
    // 验证请求体
    if (!body.content || !body.content.trim()) {
      return NextResponse.json(
        { success: false, message: '评论内容不能为空' },
        { status: 400 }
      );
    }
    
    // 查找任务
    const task = await prisma.task.findUnique({
      where: { id: taskId },
      select: { projectId: true, title: true }
    });
    
    if (!task) {
      return NextResponse.json(
        { success: false, message: '任务不存在' },
        { status: 404 }
      );
    }
    
    // 检查用户是否有权限访问该项目
    const projectUser = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId: task.projectId,
        },
      },
    });
    
    if (!projectUser) {
      return NextResponse.json(
        { success: false, message: '没有权限评论此任务' },
        { status: 403 }
      );
    }
    
    // 创建评论
    const comment = await prisma.comment.create({
      data: {
        content: body.content.trim(),
        userId,
        projectId: task.projectId,
        taskId,
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
      },
    });
    
    // 创建活动记录
    await prisma.activity.create({
      data: {
        type: "COMMENT_ADDED",
        userId,
        projectId: task.projectId,
        entityId: taskId,
        data: {
          comment: body.content.trim(),
          taskId: taskId,
          taskTitle: task.title || "未知任务"
        }
      }
    });
    
    // 如果任务有指派人且不是当前用户，发送通知
    const fullTask = await prisma.task.findUnique({
      where: { id: taskId }
    });
    
    if (fullTask?.assigneeId && fullTask.assigneeId !== userId) {
      await prisma.notification.create({
        data: {
          type: "TASK_COMMENT",
          title: "新评论",
          content: `有人在您负责的任务"${task.title || '未知任务'}"上发表了评论`,
          recipients: {
            create: {
              userId: fullTask.assigneeId
            }
          }
        }
      });
    }
    
    return NextResponse.json(
      { success: true, data: comment },
      { status: 201 }
    );
  } catch (error: any) {
    console.error('创建评论失败:', error);
    return NextResponse.json(
      { success: false, message: '创建评论失败', error: error.message },
      { status: 500 }
    );
  }
}